#include "CMap.h"
#include "CGame.h"
#pragma warning( disable : 4996 )

const int CMap::MAP_WIDTH=64;
const int CMap::MAP_HEIGHT=64;
int CMap::line_num,CMap::char_num;

BOOL CMap::MapInit(){
	if(!LoadMap())
		return FALSE;
	return TRUE;
}

void CMap::MapFin(){
	for(int i=0;i<line_num;i++){
		delete[] m_map[i];
	}
	delete[] m_map;
}

BOOL CMap::LoadMap(){
	FILE *fp;
	char buf;
	int char_buf=0,i,j;


	line_num=0;
	char_num=0;
	fp=fopen("res/map.csv","rb");
	if(fp==NULL){
		return FALSE;
	}

	while(fscanf(fp,"%c",&buf)!=EOF){
		if(buf>=0x30 && buf<=0x39){
			char_num++;
			while(fscanf(fp,"%c",&buf)!=EOF){
				if(buf>=0x30 && buf<=0x39){
				}else if(buf==0xA){
					if(!line_num)
						char_buf=char_num;
					if(char_buf!=char_num){
						fclose(fp);
						return FALSE;
					}
					line_num++;
					char_num=0;
					break;
				}else
					break;
			}
		}else if(buf==0xA){
			if(!line_num)
				char_buf=char_num;
			if(char_buf!=char_num){
				fclose(fp);
				return FALSE;
			}
			line_num++;
			char_num=0;
		}
	}
	char_num=char_buf;

	m_map=new int*[line_num];
	for(i=0;i<line_num;i++){
		m_map[i]=new int[char_num];
	}

	fseek(fp, 0, SEEK_SET);
	for(i=0,j=0;fscanf(fp,"%c",&buf)!=EOF;j++){
		if(buf>=0x30 && buf<=0x39){
			m_map[i][j]=buf-0x30;
			while(fscanf(fp,"%c",&buf)!=EOF){
				if(buf>=0x30 && buf<=0x39){
					m_map[i][j]=m_map[i][j]*10+(buf-0x30);
				}else if(buf==0xA){
					i++;
					j=-1;
					break;
				}else
					break;
			}
		}else if(buf==0xA){
			i++;
			j=-1;
		}
	}
	char_num=char_buf;

	fclose(fp);
	return TRUE;
}

void CMap::Draw(){
	for(int i=0;i<line_num;i++){
		for(int j=0;j<char_num;j++){
			if(m_map[i][j]==1){
				m_sprite.SetPos(j*64.0f,i*64.0f);
				m_sprite.Draw(CGame::GetInstance().m_GroundTex->GetTexture(),(float)MAP_HEIGHT,(float)MAP_WIDTH);
			}
		}
	}			
}